<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\UsersModel;
use App\Model\UsersPhoneLogModel;
use App\Services\Logger;
use App\Services\WechatServices;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use Illuminate\Support\Facades\DB;

class UsersDao extends BaseDao
{


    /**
     * Created by PhpStorm.
     * @purpose
     * @Author: fhc
     * @Time: 2023/5/10 14:20
     */
    public static function get_user_builder($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = UsersModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'user_phone'),function ($query)use ($params){
            $query->where('user_phone',$params['user_phone']);
        });

        $query->when(checkIsHasField($params,'point_uid'),function ($query)use ($params){
            $query->where('point_uid',$params['point_uid']);
        });

        $query->when(checkIsHasField($params,'point_uid_index'),function ($query)use ($params){
            $query->where('point_uid_index',$params['point_uid_index']);
        });


        $query->when(checkIsHasField($params,'spread_id'),function ($query)use ($params){
            $query->where('spread_id',$params['spread_id']);
        });

        $query->when(checkIsHasField($params,'vip_index'),function ($query)use ($params){
            $query->where('vip_index',$params['vip_index']);
        });


        $query->when(checkIsHasField($params,'point_uid_spread_price_id'),function ($query)use ($params){
            $query->where('point_uid_spread_price_id',$params['point_uid_spread_price_id']);
        });

        return $query;
    }

    public static function getUserInfo(array $params = []): array
    {
        $userInfo =  self::get_user_builder($params)
            ->with('vipInfo')
            ->with('spreadInfo')
            ->with('pointInfo')
            ->first()
            ->toArray();

        $userInfo['all_k_price'] = $userInfo['k_price']+BillDao::get_bill_builder([
                'type'=>3,
                'user_id'=>$userInfo['user_id'],
                'status'=>0
            ])->sum('num')+BillDao::get_bill_builder([
                'type'=>3,
                'user_id'=>$userInfo['user_id'],
                'status'=>1
            ])->sum('num');
        return $userInfo;
    }


    /**
     * @throws SysExceptions
     */
    public static function login(array $params): array
    {

        $result = WechatServices::wechat_login($params['code'],$params['iv'],$params['encryptedData'],$params['code2']);
        $userBuilder = self::get_user_builder([
            'user_phone'=>$result['phone']
        ]);
        if(!$userBuilder->exists()){
            $insertParams = [
                'user_phone'=>$result['phone'],
                'nickname'=>'面膜'.$result['phone'],
                'headimgurl'=>'https://doufu.mogooyun.com/static/my/headimgurl.jpg',
                'openid'=>$result['openid']
            ];
            //携带上级id
//            if(!checkIsHasField($params,'spread_id')){
//                self::error('没有邀请人',30001);
//            }
            if(checkIsHasField($params,'spread_id')){
                //上级邀请人
                $insertParams['spread_id'] = $params['spread_id'];
            }




            if(self::get_user_builder()->create($insertParams) === false){
                self::error('登陆失败');
            }
        }
        $userInfo = $userBuilder->first();
        return [
            'user_info'=>$userInfo
        ];
    }

    /**
     * Created by PhpStorm.
     * @purpose 设置自动任务
     * @Author: fhc
     * @Time: 2023/5/12 15:27
     */
    public static function setAutoPoint(array $array)
    {
        if(self::get_user_builder([
            'user_id'=>$array['user_id']
        ])->update([
            'is_auto'=>$array['is_auto']
        ]) === false){
            self::error('设置失败');
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function set_point_uid(array $params, $is_auto = 0)
    {
        Logger::data("===========>",[
            $params
        ]);
        //获取用户信息
        $userInfo = self::get_user_builder([
            'user_id'=>$params['user_id']
        ])->first();
        //设置的用户
        $b_uid = $params['b_uid'];
        $VipInfo = VipOrderDao::get_vip_order_builder([
            'user_id'=>$b_uid,
            'status'=>1
        ]);
        if(!$VipInfo->exists()){
            self::error('被放置人未购买VIP');
        }
        $VipInfo = $VipInfo->first()->toArray();
        $VipInfo['vip_json_info'] = json_decode($VipInfo['vip_json_info'],true);
        //放置到哪个人名下
        $pouid = $params['point_uid'];

        $poInfo = self::get_user_builder([
            'user_id'=>$pouid
        ])->first();
        if($poInfo['vip_index'] !=999){
            self::error('放置节点不正确');
        }

        //设置点位
        $pouid_index = $params['point_uid_index'];
        //从谁开始查询反费
        //第一个或者第二个点位
        $poInf = self::get_user_builder([
            'user_id'=>$pouid
        ])->first();
        if($poInf['is_zongjian'] == 1){
            $point_uid_spread_price_id = $poInf['user_id'];
        }else{
            $point_uid_spread_price_id = $poInf['point_uid_spread_price_id'];
        }
        DB::beginTransaction();
        //获取总监和合伙人反钱
        $res = UsersModel::query()->where('user_id',$b_uid)->update([
            'point_uid_index'=>$pouid_index,
            'point_uid_spread_price_id'=>$point_uid_spread_price_id,
            'point_uid'=>$pouid
        ]);

        //查询头两个点位
        if($pouid != 0){
            $count = self::get_user_builder([
                'point_uid'=>$pouid
            ])->count();
            if($count >= 2){
                //修改节点人为总监
                $res !== false && $res = self::get_user_builder([
                    'user_id'=>$pouid
                ])->update([
                    'is_zongjian'=>1
                ]);
            }
        }


        //总监销售奖励
        if($point_uid_spread_price_id != 0){
            $res !== false && $res = BillDao::get_bill_builder()->create([
                'user_id'=>$point_uid_spread_price_id,
                'pm'=>1,
                'type'=>1,
                'num'=>$VipInfo['vip_json_info']['vip_zongjian_price'],
                'title'=>'总监销售奖励'
            ]);
            $res !== false && $res = self::get_user_builder([
                'user_id'=>$point_uid_spread_price_id
            ])->increment('k_price',$VipInfo['vip_json_info']['vip_zongjian_price']);
            $df_fan = $VipInfo['vip_json_info']['vip_zongjian_price'];
            if(UsersDao::get_user_builder([
                    'user_id'=>$point_uid_spread_price_id
                ])->value('d_price') < $df_fan){
                $df_fan = UsersDao::get_user_builder([
                    'user_id'=>$point_uid_spread_price_id
                ])->value('d_price');
            }
            if($df_fan > 0) {

                $res !== false && $res = BillDao::get_bill_builder()->create([
                    'user_id' => $point_uid_spread_price_id,
                    'num' => $df_fan,
                    'pm' => 0,
                    'type' => 2,
                    'title' => '用户释放DF值'
                ]);
                $res !== false && $res = UsersDao::get_user_builder([
                    'user_id'=>$point_uid_spread_price_id
                ])->decrement('d_price',$df_fan);
            }

            $res !== false && $res = self::get_user_builder([
                'user_id'=>$point_uid_spread_price_id
            ])->increment('all_k_price',$VipInfo['vip_json_info']['vip_zongjian_price']);


            $point_uid_spread_price_info = UsersDao::get_user_builder([
                'user_id'=>$point_uid_spread_price_id
            ])->first();
            if($VipInfo['vip_json_info']['vip_sp_one_price'] > 0 && $point_uid_spread_price_info['point_uid'] != 0){
                //管理奖励总监的节点人
                $res !== false && $res = BillDao::get_bill_builder()->create([
                    'user_id'=>$point_uid_spread_price_info['point_uid'],
                    'pm'=>1,
                    'type'=>1,
                    'num'=>$VipInfo['vip_json_info']['vip_sp_one_price'],
                    'title'=>'管理奖励'
                ]);
                $res !== false && $res = self::get_user_builder([
                    'user_id'=>$point_uid_spread_price_info['point_uid']
                ])->increment('k_price',$VipInfo['vip_json_info']['vip_sp_one_price']);

                $res !== false && $res = self::get_user_builder([
                    'user_id'=>$point_uid_spread_price_info['point_uid']
                ])->increment('all_k_price',$VipInfo['vip_json_info']['vip_sp_one_price']);


                $df_fan = $VipInfo['vip_json_info']['vip_sp_one_price'];
                if(UsersDao::get_user_builder([
                        'user_id'=>$point_uid_spread_price_info['point_uid']
                    ])->value('d_price') < $df_fan){
                    $df_fan = UsersDao::get_user_builder([
                        'user_id'=>$point_uid_spread_price_info['point_uid']
                    ])->value('d_price');
                }
                if($df_fan > 0) {

                    $res !== false && $res = BillDao::get_bill_builder()->create([
                        'user_id' => $point_uid_spread_price_info['point_uid'],
                        'num' => $df_fan,
                        'pm' => 0,
                        'type' => 2,
                        'title' => '用户释放DF值'
                    ]);
                    $res !== false && $res = UsersDao::get_user_builder([
                        'user_id'=>$point_uid_spread_price_info['point_uid']
                    ])->decrement('d_price',$df_fan);
                }

            }

            $point_uid_spread_price_info = UsersDao::get_user_builder([
                'user_id'=>$point_uid_spread_price_info['point_uid']
            ]);

           if($point_uid_spread_price_info->exists()){
               $point_uid_spread_price_info = $point_uid_spread_price_info->first()->toArray();
               if($point_uid_spread_price_info['point_uid'] != 0 && $VipInfo['vip_json_info']['vip_sp_two_price'] > 0){
                   $res !== false && $res = BillDao::get_bill_builder()->create([
                       'user_id'=>$point_uid_spread_price_info['point_uid'],
                       'pm'=>1,
                       'type'=>1,
                       'num'=>$VipInfo['vip_json_info']['vip_sp_two_price'],
                       'title'=>'管理间推奖励'
                   ]);

                   $res !== false && $res = self::get_user_builder([
                       'user_id'=>$point_uid_spread_price_info['point_uid']
                   ])->increment('k_price',$VipInfo['vip_json_info']['vip_sp_two_price']);

                   $res !== false && $res = self::get_user_builder([
                       'user_id'=>$point_uid_spread_price_info['point_uid']
                   ])->increment('all_k_price',$VipInfo['vip_json_info']['vip_sp_two_price']);





                   $df_fan = $VipInfo['vip_json_info']['vip_sp_two_price'];
                   if(UsersDao::get_user_builder([
                           'user_id'=>$point_uid_spread_price_info['point_uid']
                       ])->value('d_price') < $df_fan){
                       $df_fan = UsersDao::get_user_builder([
                           'user_id'=>$point_uid_spread_price_info['point_uid']
                       ])->value('d_price');
                   }
                   if($df_fan > 0) {
                       $res !== false && $res = BillDao::get_bill_builder()->create([
                           'user_id' => $point_uid_spread_price_info['point_uid'],
                           'num' => $df_fan,
                           'pm' => 0,
                           'type' => 2,
                           'title' => '用户释放DF值'
                       ]);
                       $res !== false && $res = UsersDao::get_user_builder([
                           'user_id' => $point_uid_spread_price_info['point_uid']
                       ])->decrement('d_price', $df_fan);
                   }
               }
           }
        }







        //赠送本人DF值
        if($VipInfo['vip_json_info']['me_d_price'] > 0){
            $res !== false && $res = BillDao::get_bill_builder()->create([
                'user_id'=>$VipInfo['user_id'],
                'pm'=>1,
                'type'=>2,
                'num'=>$VipInfo['vip_json_info']['me_d_price'],
                'title'=>'赠送DF值'
            ]);
            $res !== false && $res = self::get_user_builder([
                'user_id'=>$VipInfo['user_id']
            ])->increment('d_price',$VipInfo['vip_json_info']['me_d_price']);
        }



        if($VipInfo['vip_json_info']['point_d_price'] > 0 && $userInfo['point_uid'] != 0){
            $res !== false && $res = BillDao::get_bill_builder()->create([
                'user_id'=>$userInfo['point_uid'],
                'pm'=>1,
                'type'=>2,
                'num'=>$VipInfo['vip_json_info']['point_d_price'],
                'title'=>'节点赠送DF值'
            ]);
            $res !== false && $res = self::get_user_builder([
                'user_id'=>$userInfo['point_uid']
            ])->increment('d_price',$VipInfo['vip_json_info']['point_d_price']);
        }

        if($res === false){
            DB::rollBack();
            self::error('放置失败');
        }
        DB::commit();
    }

    public static function get_user_page(array $all): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::get_user_builder($all)->with('vipInfo')->paginate();
    }

    public static function get_users_spread(array $array)
    {
        return self::get_user_builder($array)->get();
    }

    /**
     * Created by PhpStorm.
     * @purpose 获取树
     * @Author: fhc
     * @Time: 2023/5/15 10:02
     */
    public static function get_child_users_point(array $array): array
    {
        $arrData = [
            'user_info'=>self::get_user_builder([
                'user_id'=>$array['user_id']
            ])->first(),
            'child'=>[]
        ];
        $user_id = $array['user_id'];
        for ($i=1;$i<4;$i++){
            $itemUserPointInfo = self::get_user_builder([
                'point_uid'=>$user_id,
                'point_uid_index'=>$i
            ]);
            $itemData = [
                '1'=>'',
                '2'=>'',
                '3'=>""
            ];
            if($itemUserPointInfo->exists()){
                $itemUserPointInfo = $itemUserPointInfo->first()->toArray();
                $itemData['user_info'] = $itemUserPointInfo;
                $vvUserId = $itemUserPointInfo['user_id'];
                for ($a=1;$a<4;$a++){
                    $itemQuery = self::get_user_builder([
                        'point_uid'=>$vvUserId,
                        'point_uid_index'=>$a
                    ]);
                    if($itemQuery->exists()){
                        $itemData[$a] = $itemQuery->first();
                    }
                }
            }
            $arrData['child'][$i] = $itemData;
        }




        return $arrData;
    }

    /**
     * @throws InvalidArgumentException
     * @throws RuntimeException
     */
    public static function usr_qr_code(array $array)
    {
        return WechatServices::qr_code($array);
    }

    /**
     * @throws SysExceptions
     */
    public static function update_spread(array $all)
    {
        $userInfo = self::getUserInfo([
            'user_id'=>$all['user_id']
        ]);
        if($all['spread_id'] == 0){
            self::error('推荐人不正确');
        }
        $pread_info = self::get_user_builder([
            'user_phone'=>$all['spread_id']
        ]);
        if(!$pread_info->exists()){
            self::error('推荐人手机号不正确');
        }

        $res = self::get_user_builder([
            'user_id'=>$all['user_id']
        ])->update([
            'spread_id'=>$pread_info['user_id']
        ]);

        if($res === false){
            DB::rollBack();
            self::error('修改失败');
        }
        DB::commit();
    }

    /**
     * @throws SysExceptions
     */
    public static function update_user_name(array $params)
    {
        if(!checkIsHasField($params,'b_user_id')){
            self::error('请选额操作人');
        }else if(!checkIsHasField($params,'user_name')){
            self::error('请填写备注名称');
        }
        if(self::get_user_builder([
            'user_id'=>$params['b_user_id']
        ])->value('spread_id') != $params['user_id']){
            self::error('你没有权限修改');
        }
        if(self::get_user_builder([
            'user_id'=>$params['b_user_id']
        ])->update([
            'user_name'=>$params['user_name']
        ]) === false){
            self::error('修改失败');
        }
    }

    public static function update_nickname_headimgurl(array $params)
    {

        if(self::get_user_builder([
                'user_id'=>self::deleteParamId($params,'user_id')
            ])->update(self::filterFields($params,new UsersModel())) === false){
            self::error('修改失败');
        }
    }

    public static function change_yong(array $params)
    {
        //增加
        $inserLog = [
            'user_id'=>$params['user_id'],
            'pm'=>$params['change_type'],
            'type'=>2,
            'num'=>$params['num'],
            'title'=>'后台减少DF值'
        ];
        if($params['change_type'] == 1){
            $inserLog['title'] = '后台增加DF值';
        }
        DB::beginTransaction();
        $res = BillDao::get_bill_builder()->create($inserLog);
        if($params['change_type'] == 0){
            $res !== false && $res = self::get_user_builder([
                'user_id'=>$params['user_id']
            ])->decrement('d_price',$params['num']);
        }else{
            $res !== false && $res = self::get_user_builder([
                'user_id'=>$params['user_id']
            ])->increment('d_price',$params['num']);
        }
        //减少
        if($res === false){
            DB::rollBack();
            self::error('修改失败');
        }
        DB::commit();

    }

    public static function get_data_count(array $array)
    {
        $data = [
            'today_shouyi_yongjin'=>BillDao::get_bill_builder([
                'type'=>1,
                'pm'=>1,
                'user_id'=>$array['user_id']
            ])->where('created_at','>=',strtotime(date('Y-m-d')))->sum('num'),
            'shouyi_tixian'=>BillDao::get_bill_builder([
                'type'=>3,
                'user_id'=>$array['user_id']
            ])->sum('num'),
            'today_df'=>BillDao::get_bill_builder([
                'type'=>2,
                'pm'=>1,
                'user_id'=>$array['user_id']
            ])->where('created_at','>=',strtotime(date('Y-m-d')))->sum('num'),
            'df_shifang'=>BillDao::get_bill_builder([
                'user_id'=>$array['user_id'],
                'type'=>2,
                'pm'=>0
            ])->sum('num')
        ];
        return $data;
    }

    public static function set_card_json(array $array_merge)
    {
        if(!checkIsHasField($array_merge,'card_no')){
            self::error('请输入银行卡号');
        }else if(!checkIsHasField($array_merge,'card_name')){
            self::error('请输入银行名称');
        }else if (!checkIsHasField($array_merge,'card_kai')){
            self::error('请输入开户银行');
        }else if (!checkIsHasField($array_merge,'name')){
            self::error('请输入您的姓名');
        }
        if(self::get_user_builder([
            'user_id'=>$array_merge['user_id']
        ])->update([
            'bank_card_json'=>json_encode([
                'card_no'=>$array_merge['card_no'],
                'card_name'=>$array_merge['card_name'],
                'card_kai'=>$array_merge['card_kai'],
                'name'=>$array_merge['name'],
            ],JSON_UNESCAPED_UNICODE)
        ])){

        }
    }


    /**
     * @param array $params
     * @return void
     * @throws SysExceptions
     */
    public static function widthwal(array $params = []){
        $userInfo = self::get_user_builder([
            'user_id'=>$params['user_id']
        ])->first();
        if($userInfo['k_price'] < $params['money']){
            self::error('用户数量不足');
        }
        if(BillDao::get_bill_builder([
            'user_id'=>$params['user_id'],
            'status'=>0
        ])->exists()){
            self::error('当前有正在审核的提现');
        }
        DB::beginTransaction();
        $res = BillDao::get_bill_builder()->create([
            'user_id'=>$params['user_id'],
            'num'=>$params['money'],
            'pm'=>0,
            'type'=>3,
            'title'=>'用户进行提现',
            'json_data'=>json_encode($userInfo['bank_card_json']),
            'status'=>0
        ]);
        $res !== false && $res = self::get_user_builder([
            'user_id'=>$params['user_id']
        ])->decrement('k_price',$params['money']);
        if( $res=== false){
            DB::rollBack();
            self::error('提现失败');
        }
        DB::commit();
    }

    public static function get_zongjian_usrs(array $array)
    {
        return self::get_user_builder([
            'point_uid_spread_price_id'=>$array['user_id']
        ])->get();
    }

    /**
     * @param array $params
     * @return void
     * @throws InvalidArgumentException
     * @throws RuntimeException
     * @throws SysExceptions
     * @throws HttpException
     * @throws InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function user_bind_phone(array $params)
    {
        if(!checkIsHasField($params,'user_phone')){
            self::error('请填写被更改的手机号');
        }

        $result = WechatServices::wechat_login($params['code'],$params['iv'],$params['encryptedData'],$params['code2']);
        if($result['phone'] == $params['user_phone']){
            self::error('两次修改手机号一样');
        }
        if(!self::get_user_builder([
            'user_phone'=>$params['user_phone']
        ])->exists()){
            self::error('被修改用户不存在');
        }
        if(self::get_user_builder([
            'user_phone'=>$result['phone']
        ])->exists()){
            self::error('新用户已存在');
        }

        if(UsersPhoneLogModel::query()->where('b_user_phone',$result['phone'])->exists()){
            self::error('此手机号已经有过更换记录');
        }
        if(UsersPhoneLogModel::query()->create([
            'user_phone'=>$params['user_phone'],
            'b_user_phone'=>$result['phone'],
             'openid'=>$result['openid']
        ]) === false){
            self::error('提交申请成功');
        }


    }

    public static function audit_user_phone(array $all)
    {
        $info = UsersPhoneLogModel::query()
            ->where('id',$all['id'])
            ->first();
        DB::beginTransaction();
        $res = UsersPhoneLogModel::query()
            ->where('id',$all['id'])->update([
                'status'=>$all['status']
            ]);
        if($all['status'] == 1){
            $res !== false && $res = UsersDao::get_user_builder([
                'user_phone'=>$info['user_phone']
            ])->update([
                'openid'=>$info['openid'],
                'user_phone'=>$info['b_user_phone']
            ]);
        }
        if($res === false){
            DB::rollBack();
            self::error('审核失败');
        }
        DB::commit();
        return true;

    }


}
